package com.ksc.wordcount.rpc.Driver;

import akka.actor.AbstractActor;
import com.ksc.wordcount.driver.DriverEnv;
import com.ksc.wordcount.rpc.ExecutorRegister;
import com.ksc.wordcount.task.TaskStatus;
import com.ksc.wordcount.task.TaskStatusEnum;

/**
 * DriverActor是一个Akka的抽象Actor类，用于处理来自Executor的消息和注册信息。
 */
public class DriverActor extends AbstractActor {

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(TaskStatus.class, mapStatus -> {
                    // 处理TaskStatus消息
                    System.out.println("ExecutorActor received mapStatus:" + mapStatus);

                    // 如果任务状态为失败，打印错误信息
                    if (mapStatus.getTaskStatus() == TaskStatusEnum.FAILED) {
                        System.err.println("task status taskId:" + mapStatus.getTaskId());
                        System.err.println("task status errorMsg:" + mapStatus.getErrorMsg());
                        System.err.println("task status errorStackTrace:\n" + mapStatus.getErrorStackTrace());
                    }

                    // 更新任务状态到任务管理器和任务调度器中
                    DriverEnv.taskManager.updateTaskStatus(mapStatus);
                    DriverEnv.taskScheduler.updateTaskStatus(mapStatus);
                })
                .match(ExecutorRegister.class, executorRegister -> {
                    // 处理ExecutorRegister消息
                    System.out.println("ExecutorActor received executorRegister:" + executorRegister);

                    // 更新Executor注册信息到Executor管理器中
                    DriverEnv.executorManager.updateExecutorRegister(executorRegister);
                })
                .match(Object.class, message -> {
                    // 处理未能处理的消息
                    System.err.println("unhandled message:" + message);
                })
                .build();
    }
}